package org.lmind.arena.srd35.combat.action;

import org.lmind.arena.srd35.Damage;
import org.lmind.arena.srd35.DamageTypes;
import org.lmind.arena.srd35.Weapon;
import org.lmind.arena.srd35.WeaponAttributes;
import org.lmind.arena.srd35.combat.Combatant;

public class AttackAction extends AbstractCombatantAction {

	@Override
	public boolean actived(Combatant combatant) {
		return true;
	}

	@Override
	protected void doAction(Combatant combatant, Object target) {
		
		Weapon weapon = combatant.getCreature().getPrimaryWeapon();
		Combatant t = (Combatant)target;
		
		int ab = rule.attackBonus(combatant.getCreature(), weapon);
		int ac = rule.armorClass(t.getCreature(), weapon);
		int dice = rule.roll(20, 1, 0);
		
		boolean hitted = isHitted(ab, ac, dice);
		if (!hitted)
			return;
		
		Damage dmg = damage(dice, combatant, weapon);
		combatant.getCreature().hurt(dmg);
	}
	
	private boolean isHitted(int ab, int ac, int dice) {
		boolean miss = false;
		if (dice == 1) {
			miss = true;
		} else if (dice == 20) {
			miss = false;
		} else if (ab + dice >= ac) {
			miss = false;
		}
		return !miss;
	}
	
	private Damage damage(int dice, Combatant combatant, Weapon weapon) {
		int multiplying = 1;
		if (dice >= weapon.getCriticalRange()) {
			multiplying = weapon.getCriticalFactor();
		}
		Damage dmg = new Damage();
		for (int i = 0; i < multiplying; i++) {
			dmg.add(DamageTypes.PHYSICAL, rule.range(weapon.getMinDamage(), weapon.getMaxDamage()));
			// 伤害里累加力量加值
			if (Boolean.TRUE.equals(weapon.getAttribute(WeaponAttributes.HAS_STRENGTH_BONUS))) {
				dmg.add(DamageTypes.PHYSICAL, rule.abilityModifier(combatant.getCreature().getStrength()));
			}
		}
		return dmg;
	}

}
